﻿Imports System.Text.RegularExpressions
Imports HtmlAgilityPack

Public Class ATV
    Inherits WebSite

    Private Enum A3Sections
        Home = 100

        SeriesHome = 200
        SeriesSeasons = 201
        SeriesEpisodes = 202

        NoticiasHome = 300
        NoticiasYears = 301
        NoticiasMonths = 302
        NoticiasEpisodes = 303

        ProgramasHome = 400
        ProgramasYears = 401
        ProgramasMonths = 402
        ProgramasEpisodes = 403

        InfantilesHome = 500
        InfantilesSeasons = 501
        InfantilesEpisodes = 502

        MoviesHome = 600
    End Enum

    Private htmlDoc As HtmlDocument

    Public Sub New()
        MyBase.BaseURL = "http://play.tuteve.tv/"
        MyBase.Name = "ATV"
        MyBase.Site = WebSites.Antena3

        htmlDoc = New HtmlDocument()
    End Sub

    Public Overrides Function GetCategories() As System.Collections.Generic.List(Of Category)
        Dim webData As String = SiteUtilBase.GetWebData(MyBase.BaseURL)

        htmlDoc.LoadHtml(webData)
        Return GetMenuItems(htmlDoc.DocumentNode.SelectNodes("//div[./@id=""menuPrincipal""]/div/*"))
    End Function

    Public Overrides Function GetSubCategories(parentCategory As Category) As System.Collections.Generic.List(Of Category)
        Dim link = CType(parentCategory, RssLink)
        Dim node As HtmlNode = htmlDoc.DocumentNode.SelectSingleNode(link.Url)

        Return GetMenuItems(node.SelectNodes("./div[1]//a[./@class=""item""]"))
    End Function

    Private Function GetMenuItems(nodes As HtmlNodeCollection) As List(Of Category)
        Dim items As New List(Of Category)

        If nodes Is Nothing Then Return items

        For Each item In nodes
            Dim newCat = New RssLink()
            If item.OriginalName = "a" Then
                If Not item.GetAttributeValue("style", "").Contains("display:none") Then
                    newCat.Name = item.InnerText
                    Dim url = item.GetAttributeValue("href", "")
                    If url <> "/" AndAlso url <> "#" Then url = TVALaCartaUtil.CombinePath(url, "/1")
                    newCat.Url = TVALaCartaUtil.CombinePath(MyBase.BaseURL, url)
                End If
            ElseIf item.OriginalName = "div" Then
                newCat.Name = Web.HttpUtility.HtmlDecode(item.FirstChild().InnerText.Trim())
                newCat.HasSubCategories = True
                newCat.Url = item.XPath
            End If

            If newCat.Name <> "" Then
                newCat.Name = Web.HttpUtility.HtmlDecode(newCat.Name)
                items.Add(newCat)
            End If
        Next

        Return items
    End Function

    Public Overrides Function GetVideos(category As Category) As List(Of VideoInfo)
        Dim videos As New List(Of VideoInfo)
        Dim link = CType(category, RssLink)
        Dim webData = SiteUtilBase.GetWebData(link.Url)

        Dim videoDoc As HtmlDocument = New HtmlDocument()
        videoDoc.LoadHtml(webData)
        For Each videoItem In videoDoc.DocumentNode.SelectNodes("//a[./@id=""itmVideo1""]")
            Dim newVideo = New VideoInfo()
            newVideo.Title = Web.HttpUtility.HtmlDecode(videoItem.SelectNodes(".//div[./@class=""tituloItem""]")(0).InnerText)
            newVideo.VideoUrl = TVALaCartaUtil.CombinePath(BaseURL, videoItem.GetAttributeValue("href", ""))
            newVideo.ImageUrl = videoItem.SelectNodes(".//img[./@class=""imgVideo""]")(0).GetAttributeValue("src", "")
            newVideo.Airdate = videoItem.SelectNodes(".//span[./@class=""fechaItem""]")(0).InnerText
            newVideo.Description = Web.HttpUtility.HtmlDecode(videoItem.SelectNodes(".//div[./@class=""introItem""]")(0).InnerText)

            videos.Add(newVideo)
        Next

        Return videos
    End Function

    Public Overrides Function GetVideoURL(video As VideoInfo) As String
        Dim webData = SiteUtilBase.GetWebData(video.VideoUrl)

        ' TODO: Live videos do not work yet.
        Dim url = "http://play.tuteve.tv/brightcovevideo/{0}/default/618/354/{1}/true"
        Dim m = Regex.Match(webData, "<script\slanguage=""javascript"">\s*setVideoFrame\('(?<videoId>[^']*)',(?:(?!@@).)*,'bc','(?<certPath>[^']*)','(?:(?!@@).)*',\s'true'\);\s*</script>")
        If Not m.Success Then m = Regex.Match(webData, "setVideoFrame\('(?<videoId>[^']*)',(?:(?!@@).)*,'bc','(?<certPath>[^']*)','(?:(?!@@).)*',\s*'true'\)")

        If m.Success Then
            url = String.Format(url, m.Groups("videoId").Value, m.Groups("certPath").Value)

            Dim bc = New BrightCove(video, url, m.Groups("videoId").Value, m.Groups("certPath").Value)
            Return bc.GetVideoURL()
        End If

        Return ""
    End Function
End Class
